package bank;

import java.util.Stack;

public class _20ValidBrackets {
    public static boolean isValid(String s) {
        int len = s.length();
        if(len < 2){
            return false;
        }
        char[] sChars = s.toCharArray();
        //先添加一个栈
        Stack<Character> area = new Stack<>();
        for(int i = 0;i < len;i++){
            //判断入栈条件
            if(canPush(sChars[i])){
                area.add(sChars[i]);
                continue;
            }else {
                //遇到了反括号怎么处理
                //注意这里必须有判占空的方法，否则会抛异常！java.util.EmptyStackException
                if(area.isEmpty()) return false;
                if(ifMatch(area.peek(),sChars[i])){
                    //出栈
                    area.pop();
                    continue;
                }else {
                    return false;
                }
            }
        }
        return area.isEmpty() ? true : false;
    }

    private static boolean ifMatch(Character peek,char sChar) {
        if(peek == '(' && sChar == ')'){
            return true;
        }else if (peek == '[' && sChar == ']'){
            return true;
        }else if (peek == '{' && sChar == '}'){
            return true;
        }else {
            return false;
        }
    }

    private static boolean canPush(char sChar) {
        if(sChar=='(' || sChar=='[' || sChar=='{'){
            return true;
        }else {
            return false;
        }
    }
}
